//
//  ZGWFindPeopleWithConditionResultViewController.m
//  1gene
//
//  Created by 张国文 on 16/6/20.
//  Copyright © 2016年 1jiyin. All rights reserved.
//

#import "ZGWFindPeopleWithConditionResultViewController.h"
#import "FriendMessageTableViewCell.h"
#import "FriendIDCheckViewController.h"
#import "MyChatViewController.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface ZGWFindPeopleWithConditionResultViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *findWithConditonTableView;
@property (nonatomic, assign) BOOL canClickGuanZhu; // 是否可以点击关注

@end

@implementation ZGWFindPeopleWithConditionResultViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    // 布局
    [self addMySubview];
    self.canClickGuanZhu = YES;
}

// navi的修改
- (void)changeNavigation
{
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationItem.title = @"搜索结果";
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 布局
- (void)addMySubview
{
    self.findWithConditonTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
    self.findWithConditonTableView.backgroundColor = [UIColor whiteColor];
    self.findWithConditonTableView.dataSource = self;
    self.findWithConditonTableView.delegate = self;
    self.findWithConditonTableView.bounces = NO;
    self.findWithConditonTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_findWithConditonTableView];
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.findWithConditonResultArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"friendMessage";
    FriendMessageTableViewCell *cell = [[FriendMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 获取model
    if (self.findWithConditonResultArray.count > indexPath.row) {
        cell.zgwSearchFriendModel = self.findWithConditonResultArray[indexPath.row];
    }
    
    [cell.attentionButton addTarget:self action:@selector(clickButtonOnResult:) forControlEvents:UIControlEventTouchUpInside];
    cell.attentionButton.tag = 200;
    [cell.addFriendButton addTarget:self action:@selector(clickButtonOnResult:) forControlEvents:UIControlEventTouchUpInside];
    cell.addFriendButton.tag = 201;
    return cell;
}

#pragma mark - button的点击事件
- (void)clickButtonOnResult:(UIButton *)button
{
    UIView *v = [button superview];
    FriendMessageTableViewCell *cell = (FriendMessageTableViewCell *)[v superview];
    NSIndexPath *tempIndexPath = [self.findWithConditonTableView indexPathForCell:cell];
    switch (button.tag) {
        case 200:
        {
            // 说明是关注好友
            NSLog(@"关注好友, row = %ld", tempIndexPath.row);
            ZGWSearchFriendModel *searchModel = self.findWithConditonResultArray[tempIndexPath.row];
            NSString *isAttention = [NSString stringWithFormat:@"%@", searchModel.is_attention];
            if ([isAttention isEqualToString:@"1"]) {
                NSLog(@"已经关注");
            } else if ([isAttention isEqualToString:@"0"]) {
                NSLog(@"进行关注");
                if (self.canClickGuanZhu == YES) {
                    self.canClickGuanZhu = NO;
                    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
                    // 关注url
                    NSString *attentionUserUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWAttentionUser, kCurrentUserToken];
                    NSDictionary *paramaterDic = @{@"attention_user":searchModel.user_id};
                    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                    [manager POST:attentionUserUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
                        self.canClickGuanZhu = YES;
                        NSDictionary *statusDic = [responseObject valueForKey:@"status"];
                        NSString *msgString = [statusDic valueForKey:@"msg"];
                        if ([msgString isEqualToString:@"关注成功"]) {
                            searchModel.is_attention = [NSString stringWithFormat:@"%d", 1];
                            [self.findWithConditonTableView reloadData];
                        }
                    } failure:^(NSURLSessionDataTask *task, NSError *error) {
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提醒" Content:@"关注失败" ToView:self];
                        self.canClickGuanZhu = YES;
                    }];
                }
            }
            break;
        }
        case 201:
        {
            // 说明是添加好友
            NSLog(@"添加好友,row = %ld", tempIndexPath.row);
            ZGWSearchFriendModel *searchModel = self.findWithConditonResultArray[tempIndexPath.row];
            NSString *isFriend = [NSString stringWithFormat:@"%@", searchModel.is_friend];
            if ([isFriend isEqualToString:@"1"]) {
                NSLog(@"已经是好友");
            } else if ([isFriend isEqualToString:@"0"]) {
                NSLog(@"添加好友");
                FriendIDCheckViewController *friendIDCheckVC = [[FriendIDCheckViewController alloc] init];
                
                friendIDCheckVC.targetUserID = searchModel.user_id;
                friendIDCheckVC.currentUserName = searchModel.nikename;
                [self.navigationController pushViewController: friendIDCheckVC animated:YES];
            }
            break;
        }
        default:
            break;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 动态布局
    FriendMessageTableViewCell *cell = (FriendMessageTableViewCell *)[self tableView:self.findWithConditonTableView cellForRowAtIndexPath:indexPath];
    return cell.geneSimilarityLabel.bottom + 13 * kAdjustParamater;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyChatViewController *myChatVC = [[MyChatViewController alloc] init];
    myChatVC.conversationType = ConversationType_PRIVATE;
    if (self.findWithConditonResultArray.count > indexPath.row) {
        ZGWSearchFriendModel *model = self.findWithConditonResultArray[indexPath.row];
        NSLog(@"姓名:%@", model.nikename);
        myChatVC.targetId = model.user_id;
        myChatVC.title = model.nikename;
    }
    
    [self.navigationController pushViewController:myChatVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
